#coding: utf-8

import config
from config_loader import FileSystemConfigLoader, WebPageConfigLoader
from book_data_processor import BookDataProcessor
from utils.logger_factory import LOG_ERR, LOG_INFO
from dao.data_feed_dao import DataFeedDAO

class XmlUpgrader(object):
    @classmethod
    def process_single_xml(cls, data_feed):
        data_type = None
        is_delta = False

        if config.CHILDREN_BOOK_PREFIX in data_feed._file_name:
            data_type = config.BookConfig.CNBOOKS_CHILDREN_TYPE
        elif config.IMPORTED_BOOK_PREFIX:
            data_type = config.BookConfig.CNBOOKS_IMPORTED_TYPE
        else:
            return

        if "delta" in data_feed._file_name:
            is_delta = True

        processor = BookDataProcessor()
        processor.process(data_feed._path, data_type, is_delta)
        processor.close()

class FileSystemUpgrader(XmlUpgrader):
    @classmethod
    def process(cls):
        data_feeds = FileSystemConfigLoader.load()
        dao = DataFeedDAO()
        for data_feed in data_feeds:
            cls.process_single_xml(data_feed)
            dao.save_or_update(data_feed)
            LOG_INFO("upgrade file from filesystem: %s" % data_feed)
        dao.close()

class WebPageUpgrader(XmlUpgrader):
    @classmethod
    def process(cls):
        data_feeds = WebPageConfigLoader.load()
        dao = DataFeedDAO()
        for data_feed in data_feeds:
            cls.process_single_xml(data_feed)
            dao.save_or_update(data_feed)
            LOG_INFO("upgrade file from web: %s" % data_feed)
        dao.close()

if __name__ == "__main__":
    FileSystemUpgrader.process()
    WebPageUpgrader.process()
